// pages/Song/Song.js
import request from '../../utils/request';
import PubSub from 'pubsub-js';
import moment from 'moment';
const appInstance = getApp();

Page({
  data: {
    isPlay: false,
    isLoading: false,
    song: {},
    songId: '',
    currentTime: '00:00',
    durationTime: '00:00',
    currentWidth: 0,
    lyrics: ['', '', ''],
    lyricList: [],
    currentLyricIndex: 1,
    isDragging: false,
    dragStartX: 0,
    dragStartWidth: 0,
    loopMode: 0, // 0-循环 1-随机 2-单曲
    collectedSongs: [],
  },

  onLoad(options) {
    const app = getApp();
    let songId = options.ids;
    
    if (app.globalData.pendingSong) {
      this.initWithPendingSong(app.globalData.pendingSong);
      app.globalData.pendingSong = null;
      songId = this.data.song.id;
    }
    
    this.setData({ 
      songId,
      loopMode: appInstance.globalData.loopMode || 0,
      collectedSongs: wx.getStorageSync('collectedSongs') || []
    });

    if (songId) {
      this.getMusic(songId).then(() => {
        this.musicControl(true, songId);
        // 添加到播放列表
        this.addToPlaylist(this.data.song);
      });
      this.getLyric(songId);
    }

    if (appInstance.globalData.isMusicPlay && appInstance.globalData.songId === songId) {
      this.setData({ isPlay: true });
    }

    this.initAudioManager();
  },

  initWithPendingSong(song) {
    this.setData({
      song: {
        id: song.id,
        name: song.name,
        ar: song.ar,
        al: song.al,
        dt: song.dt
      },
      durationTime: moment(song.dt).format('mm:ss')
    });
    wx.setNavigationBarTitle({ title: song.name });
  },

  initAudioManager() {
    this.backgroundAudioManager = wx.getBackgroundAudioManager();
    this.setupAudioManagerEvents();
  },

  setupAudioManagerEvents() {
    const manager = this.backgroundAudioManager;
    
    manager.onPlay(() => {
      this.changePlayState(true);
      appInstance.globalData.songId = this.data.songId;
    });
    
    manager.onPause(() => {
      this.changePlayState(false);
    });
    
    manager.onStop(() => {
      this.changePlayState(false);
    });
    
    manager.onEnded(() => {
      const { loopMode } = this.data;
      
      if (loopMode === 2) { // 单曲循环
        this.setData({
          currentWidth: 0,
          currentTime: '00:00',
          lyrics: ['', '', ''],
          isPlay: true
        });
        this.singleLoopRetryCount = 0;
        this.handleSingleLoop();
        return;
      }
      
      if (loopMode === 1) { // 随机播放
        this.playRandomSong();
      } else { // 顺序播放
        PubSub.publish('switchType', 'next');
      }
      
      this.setData({
        currentWidth: 0,
        currentTime: '00:00',
        lyrics: ['', '', ''],
      });
    });
    
    manager.onTimeUpdate(() => {
      if (!this.data.isDragging && !manager.paused) {
        let currentTime = moment(manager.currentTime * 1000).format('mm:ss');
        let currentWidth = (manager.currentTime / manager.duration) * 100;
        this.setData({
          currentTime,
          currentWidth,
        });
        this.updateLyric();
      }
    });
    
    manager.onError((err) => {
      console.error('播放器错误:', err);
      wx.showToast({ title: '播放出错', icon: 'none' });
    });
  },

  addToPlaylist(song) {
    const { playList } = appInstance.globalData;
    const existingIndex = playList.findIndex(item => item.id === song.id);
    
    if (existingIndex === -1) {
      appInstance.globalData.playList.push(song);
      appInstance.globalData.currentIndex = appInstance.globalData.playList.length - 1;
    } else {
      appInstance.globalData.currentIndex = existingIndex;
    }
  },

  playRandomSong() {
    const { playList } = appInstance.globalData;
    if (playList.length === 0) {
      wx.showToast({ title: '播放列表为空', icon: 'none' });
      return;
    }

    let randomIndex;
    do {
      randomIndex = Math.floor(Math.random() * playList.length);
    } while (playList.length > 1 && randomIndex === appInstance.globalData.currentIndex);

    const randomSong = playList[randomIndex];
    appInstance.globalData.currentIndex = randomIndex;
    
    this.setData({
      songId: randomSong.id,
      song: randomSong,
      durationTime: moment(randomSong.dt).format('mm:ss')
    });
    
    this.getLyric(randomSong.id);
    this.musicControl(true, randomSong.id);
    wx.setNavigationBarTitle({ title: randomSong.name });
  },

  handleSingleLoop() {
    if (this.singleLoopRetryCount > 2) return;

    this.singleLoopRetryCount++;
    
    this.setData({ isLoading: true });
    
    this.backgroundAudioManager.stop();
    this.initAudioManager();
    
    this.musicControl(true, this.data.songId)
      .then(() => {
        setTimeout(() => {
          this.backgroundAudioManager.seek(0);
          this.setData({ isLoading: false });
        }, 500);
      })
      .catch(() => {
        this.setData({ isLoading: false });
        setTimeout(this.handleSingleLoop.bind(this), 1000);
      });
  },

  changeLoop() {
    const newMode = (this.data.loopMode + 1) % 3;
    this.setData({ loopMode: newMode });
    wx.showToast({
      title: ['列表循环', '随机播放', '单曲循环'][newMode],
      icon: 'none'
    });
    appInstance.globalData.loopMode = newMode;
  },

  changePlayState(isPlay) {
    this.setData({ isPlay });
    appInstance.globalData.isMusicPlay = isPlay;
  },

  ChangeMusicPlay() {
    let isPlay = !this.data.isPlay;
    let { songId } = this.data;
    this.musicControl(isPlay, songId);
  },

  async musicControl(isPlay, songId) {
    this.setData({ isLoading: true });
    
    try {
      if (isPlay) {
        let musicLinkData = await request('/song/url', { id: songId });
        let musicLink = musicLinkData.data[0].url;
        
        if (!musicLink) throw new Error('无有效播放链接');
        
        this.backgroundAudioManager.src = musicLink;
        this.backgroundAudioManager.title = this.data.song.name;
        this.backgroundAudioManager.epname = this.data.song.al.name;
        this.backgroundAudioManager.singer = this.data.song.ar.map(artist => artist.name).join('/');
        this.backgroundAudioManager.coverImgUrl = this.data.song.al.picUrl;
        this.backgroundAudioManager.startTime = 0;
        
        if (wx.getSystemInfoSync().platform === 'android') {
          setTimeout(() => {
            this.backgroundAudioManager.play();
          }, 200);
        }
        
        this.setData({ isPlay: true });
        appInstance.globalData.isMusicPlay = true;
        appInstance.globalData.songId = songId;
      } else {
        this.backgroundAudioManager.pause();
        appInstance.globalData.isMusicPlay = false;
      }
    } catch (error) {
      console.error('播放控制失败:', error);
      wx.showToast({ title: '操作失败', icon: 'none' });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  async getMusic(songId) {
    try {
      let songData = await request('/song/detail', { ids: songId });
      let durationTime = moment(songData.songs[0].dt).format('mm:ss');
      if (songData?.songs?.length > 0) {
        const song = songData.songs[0];
        this.setData({
          song,
          durationTime,
        });
        
        const index = appInstance.globalData.playList.findIndex(s => s.id === song.id);
        if (index === -1) {
          appInstance.globalData.playList.push(song);
          appInstance.globalData.currentIndex = appInstance.globalData.playList.length - 1;
        } else {
          appInstance.globalData.currentIndex = index;
        }
        
        wx.setNavigationBarTitle({ title: song.name });
      }
    } catch (error) {
      console.error('获取歌曲详情失败:', error);
      wx.showToast({ title: '加载失败', icon: 'none' });
    }
  },

  async getLyric(songId) {
    try {
      const res = await request('/lyric', { id: songId });
      if (res.code === 200) {
        const lyricStr = res.lrc.lyric;
        const lyricList = this.parseLyric(lyricStr);
        this.setData({ lyricList });
      }
    } catch (error) {
      console.error('获取歌词失败:', error);
    }
  },

  parseLyric(lyricStr) {
    const lines = lyricStr.split('\n');
    const lyricList = [];
    lines.forEach(line => {
      const match = line.match(/\[(\d{2}):(\d{2})\.(\d{2,3})\](.*)/);
      if (match) {
        const time = parseInt(match[1]) * 60 + parseFloat(match[2] + '.' + match[3]);
        const text = match[4].trim();
        lyricList.push({ time, text });
      }
    });
    return lyricList;
  },

  collectSong() {
    const { song } = this.data;
    let collectedSongs = wx.getStorageSync('collectedSongs') || []; 
    const newSong = {
      id: song.id,
      name: song.name,
      artist: song.ar[0].name,
      cover: song.al.picUrl,
      duration: song.dt,
      al: song.al,
      ar: song.ar
    };
    const existingIndex = collectedSongs.findIndex(item => item.id === newSong.id);
    
    if (existingIndex === -1) {
      const newCollected = [newSong, ...collectedSongs];
      wx.setStorageSync('collectedSongs', newCollected);
      this.setData({ 
        collectedSongs: newCollected,
        ['song.isCollected']: true 
      });
      wx.showToast({ title: '已收藏', icon: 'success' });
    } else {
      const newCollected = collectedSongs.filter(item => item.id !== newSong.id);
      wx.setStorageSync('collectedSongs', newCollected);
      this.setData({ 
        collectedSongs: newCollected,
        ['song.isCollected']: false 
      });
      wx.showToast({ title: '已取消收藏', icon: 'success' });
    }
  },

  updateLyric() {
    const { lyricList } = this.data;
    const currentTime = this.backgroundAudioManager.currentTime;

    if (lyricList.length === 0) return;

    let currentIndex = 0;
    for (let i = 0; i < lyricList.length; i++) {
      if (lyricList[i].time > currentTime) break;
      currentIndex = i;
    }

    const lyrics = [
      lyricList[currentIndex - 1]?.text || '',
      lyricList[currentIndex]?.text || '',
      lyricList[currentIndex + 1]?.text || '',
    ];
    this.setData({ lyrics, currentLyricIndex: 1 });
  },

  handleSwitch(event) {
    let type = event.currentTarget.id;
    if (type === 'random') {
      this.playRandomSong();
    } else {
      PubSub.publish('switchType', type);
    }
  },

  onTouchStart(e) {
    this.setData({
      isDragging: true,
      dragStartX: e.touches[0].clientX,
      dragStartWidth: this.data.currentWidth
    });
  },

  onTouchMove(e) {
    if (this.data.isDragging) {
      const deltaX = e.touches[0].clientX - this.data.dragStartX;
      const newWidth = this.data.dragStartWidth + (deltaX / 450) * 100;
      const clampedWidth = Math.max(0, Math.min(newWidth, 100));
      this.setData({ currentWidth: clampedWidth });
    }
  },

  onTouchEnd() {
    if (this.data.isDragging) {
      const newTime = (this.data.currentWidth / 100) * this.backgroundAudioManager.duration;
      this.backgroundAudioManager.seek(newTime);
      this.setData({ isDragging: false });
    }
  },

  onShow() {
    if (appInstance.globalData.songId === this.data.songId) {
      this.setData({
        isPlay: appInstance.globalData.isMusicPlay
      });
    }
  },

  onUnload() {
    // 清理工作
  }
});